package com.tom.imooc.dynamicdatasource;

import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zx
 * @date 2024年12月16日 20:27
 */
@Configuration
public class SpringDataSourceConfiguration {

    @Bean
    public DataSource userDataSource() {
        return DataSourceBuilder.create().
                driverClassName("com.mysql.jdbc.Driver").
                url("jdbc:mysql://localhost:3306/test_user?characterEncoding=utf8").
                username("root").
                password("123456").build();
    }

    @Bean
    public DataSource orderDataSource() {
        return DataSourceBuilder.create().
                driverClassName("com.mysql.jdbc.Driver").
                url("jdbc:mysql://localhost:3306/test_order?characterEncoding=utf8").
                username("root").
                password("123456").build();
    }


    @Primary //指定主数据源
    @Bean
    public SpringDynamicDataSource springDynamicDataSource() {
        Map<Object, Object> targetDataSources = new HashMap<>();
        DataSource userDataSource = userDataSource();
        DataSource orderDataSource = orderDataSource();
        targetDataSources.put("test_user", userDataSource);
        targetDataSources.put("test_order", orderDataSource);
        return new SpringDynamicDataSource(targetDataSources);
    }


}
